import utils from '../../modules/utils'
import {sessionStore} from "../bianmaba-store"
import Vue from "vue";
import axios from 'axios'
import Login from "./Login";

//显示登录窗口函数
const login = function (url) {
  let LoginCmp = new Vue(Vue.extend({
    template: '<login isPage="false" loginUrl="' + url + '"></login>', components: {Login}
  })).$mount();
  document.getElementById('app').appendChild(LoginCmp.$el)
}

const BianmabaAuth = {
  install: function (Vue, options = {router: null, loginUrl: "/login"}) {
    console.log("plugin:bianmaba-auth load...")
    if (utils.isEmpty(options.router)) {
      throw "Router option is required and cannot be empty.";
    }
    if (utils.isEmpty(options.loginUrl)) {
      throw "LoginUrl option is required and cannot be empty.";
    }

    //处理ajax请求认证，判断是否需要弹出登录窗口
    axios.interceptors.request.use(config => {
      let user = sessionStore.get("user");
      config.headers['request_type'] = 'ajax';
      if (!utils.isEmpty(user) && user.hasOwnProperty("token")) {
        config.headers['token'] = sessionStore.get("user").token;
      }
      return config
    }, error => {
      return Promise.reject(error)
    });
    axios.interceptors.response.use(response => {
        return response
      }, error => {
        if (error.response.status == 401) {
          //store.remove("user")
          login(options.loginUrl);
        }
        Vue.prototype.$message.error(error.response.data.result)
        return Promise.reject(error)
      }
    )

    Vue.$login = Vue.login = login;

    //动态登录页面到路由节点
    const matchedComponents = options.router.getMatchedComponents("/login")
    if (matchedComponents.length <= 0) {
      options.router.addRoutes([{
        path: "/login",
        component: function (resolve) {
          require(['./Login'], resolve)
        },
        props: {isPage: true, loginUrl: options.loginUrl}
      }]);
    }

    //处理页面跳转的认证，如果无谁则跳转到登录页面
    options.router.beforeEach((to, from, next) => {
      if (to.path != "/login") {
        const user = sessionStore.get("user");
        if (user == undefined || !user.hasOwnProperty("token")) {
          next("/login")
        } else {
          next();
        }
      } else {
        next();
      }
    })
  }
}


export default BianmabaAuth
